package com.eastfair.certificate.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.annotation.annotation.cache.Cache;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.dto.UserAccountDto;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.builder.ExhibitorFeign;
import com.eastfair.builder.vo.ExhibitorVO;
import com.eastfair.cache.certificate.CertificateOrderCacheKeyBuilder;
import com.eastfair.certificate.dao.CertificateOrderMapper;
import com.eastfair.certificate.dto.CertificateOrderDTO;
import com.eastfair.certificate.dto.CertificateUserDTO;
import com.eastfair.certificate.dto.TakeApplyerDTO;
import com.eastfair.certificate.entity.Certificate;
import com.eastfair.certificate.entity.CertificateOrder;
import com.eastfair.certificate.entity.CertificateUser;
import com.eastfair.certificate.enumeration.*;
import com.eastfair.certificate.exceptioncode.CertificateExceptionCode;
import com.eastfair.certificate.service.CertificateOrderService;
import com.eastfair.certificate.service.CertificateService;
import com.eastfair.certificate.service.CertificateUserService;
import com.eastfair.certificate.vo.CertificateOrderVO;
import com.eastfair.certificate.vo.CertificateUserVO;
import com.eastfair.common.api.*;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.core.utils.BeanPlusUtil;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.database.mybatis.conditions.Wraps;
import com.eastfair.database.mybatis.conditions.query.QueryWrap;
import com.eastfair.database.mybatis.typehandler.TypeHandlerUtil;
import com.eastfair.pay.dto.InvoiceApplyerDTO;
import com.eastfair.pay.dto.TransactionDTO;
import com.eastfair.pay.dto.TransactionOrderDTO;
import com.eastfair.pay.enumeration.TransactionOrderOrderStatusEnum;
import com.eastfair.pay.enumeration.TransactionOrderOrderTypeEnum;
import com.eastfair.pay.enums.InvoiceApplyBusinessTypeEnum;
import com.eastfair.pay.enums.PayChannelEnum;
import com.eastfair.pay.enums.PayTypeEnum;
import com.eastfair.pay.enums.TransactionStatusEnum;
import com.eastfair.pay.enums.TranstionTypeEnum;
import com.eastfair.pay.vo.ApplyRefundVO;
import com.eastfair.pay.vo.InvoiceApplyerVO;
import com.eastfair.venuebooking.api.ExhibitionManageFeign;
import com.eastfair.venuebooking.api.ServiceProviderFeign;
import com.eastfair.venueservice.dto.ExhibitionManageQuery;
import com.eastfair.venueservice.dto.ServiceProviderDTO;
import com.eastfair.venueservice.vo.ExhibitionManageVO;
import com.eastfair.venueservice.vo.ServiceProviderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 制证订单
 * </p>
 *
 * @author ligang
 * @date 2022-08-02
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class CertificateOrderServiceImpl extends SuperCacheServiceImpl<CertificateOrderMapper, CertificateOrder> implements CertificateOrderService {

    @Autowired
    CertificateUserService certificateUserService;
    @Autowired
    CertificateService certificateService;


    @Autowired
    ServiceProviderFeign serviceProviderFeign;

    @Autowired
    ExhibitionManageFeign exhibitionManageFeign;

    @Autowired
    UserAccountServiceFeign userAccountServiceFeign;

    @Autowired
    InvoiceApplyerFeign invoiceApplyerFeign;

    @Autowired
    InvoiceFeign invoiceFeign;

    @Autowired
    TransactionOrderFeign transactionOrderFeign;

    @Autowired
    TransactionFeign transactionFeign;

    @Autowired
    ExhibitorFeign exhibitorFeign;

    @Autowired
    ApplyRefundFeign applyRefundFeign;

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(CertificateOrder model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTeamId(ContextUtil.getTeamId());
        model.setIsDeleted(BusinessConstant.NO);
        model.setIsEnabled(BusinessConstant.YES);
        //雪花ID
        return R.successDef();
    }

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<CertificateOrder> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<CertificateOrder> list(CertificateOrderDTO modelDTO, List<Long> ids) {
        return ((CertificateOrderService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'certificateUserId', #args[0]?.certificateUserId}," +
                            "{'costMoney', #args[0]?.costMoney}," +
                            "{'overTimeMoney', #args[0]?.overTimeMoney}," +
                            "{'depositMoney', #args[0]?.depositMoney}," +
                            "{'returnMoney', #args[0]?.returnMoney}," +
                            "{'returnType', #args[0]?.returnType}," +
                            "{'voucherNumber', #args[0]?.voucherNumber}," +
                            "{'returnLabel', #args[0]?.returnLabel}," +
                            "{'companyId', #args[0]?.companyId}," +
                            "{'isDraw', #args[0]?.isDraw}," +
                            "{'isTake', #args[0]?.isTake}," +
                            "{'isPay', #args[0]?.isPay}," +
                            "{'isPrintTake', #args[0]?.isPrintTake}," +
                            "{'isCancel', #args[0]?.isCancel}," +
                            "{'isReturn', #args[0]?.isReturn}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'returnOrderStatus', #args[0]?.returnOrderStatus}," +
                            "{'orderNumber', #args[0]?.orderNumber}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<CertificateOrder> listOfCache(CertificateOrderDTO modelDTO, List<Long> ids) {
        //查询
        CertificateOrder certificateOrder = new CertificateOrder();
        if (modelDTO != null) {
            BeanUtils.copyProperties(modelDTO, certificateOrder);
        }
        //查询加密处理
//        if (StringUtils.isNotBlank(certificateOrder.getDrawIdcard())) {
//            certificateOrder.setDrawIdcard(TypeHandlerUtil.crypt(certificateOrder.getDrawIdcard()));
//        }
//        if (StringUtils.isNotBlank(certificateOrder.getDrawMobile())) {
//            certificateOrder.setDrawMobile(TypeHandlerUtil.crypt(certificateOrder.getDrawMobile()));
//        }
        QueryWrap<CertificateOrder> queryWrapper = Wraps.q(certificateOrder);

//        if (modelDTO != null) {
//            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getOrderNumber()), CertificateOrder::getOrderNumber, modelDTO.getOrderNumber());
//            queryWrapper.lambda().eq(modelDTO.getCostMoney() != null, CertificateOrder::getCostMoney, modelDTO.getCostMoney());
//            queryWrapper.lambda().eq(modelDTO.getOverTimeMoney() != null, CertificateOrder::getOverTimeMoney, modelDTO.getOverTimeMoney());
//            queryWrapper.lambda().eq(modelDTO.getDepositMoney() != null, CertificateOrder::getDepositMoney, modelDTO.getDepositMoney());
//            queryWrapper.lambda().eq(modelDTO.getReturnMoney() != null, CertificateOrder::getReturnMoney, modelDTO.getReturnMoney());
//            queryWrapper.lambda().eq(modelDTO.getReturnType() != null, CertificateOrder::getReturnType, modelDTO.getReturnType());
//            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getVoucherNumber()), CertificateOrder::getVoucherNumber, modelDTO.getVoucherNumber());
//            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getReturnLabel()), CertificateOrder::getReturnLabel, modelDTO.getReturnLabel());
//            queryWrapper.lambda().eq(modelDTO.getCompanyId() != null, CertificateOrder::getCompanyId, modelDTO.getCompanyId());
//            queryWrapper.lambda().eq(modelDTO.getIsDraw() != null, CertificateOrder::getIsDraw, modelDTO.getIsDraw());
//            queryWrapper.lambda().eq(modelDTO.getIsTake() != null, CertificateOrder::getIsTake, modelDTO.getIsTake());
//            queryWrapper.lambda().eq(modelDTO.getIsPay() != null, CertificateOrder::getIsPay, modelDTO.getIsPay());
//            queryWrapper.lambda().eq(modelDTO.getIsPrintTake() != null, CertificateOrder::getIsPrintTake, modelDTO.getIsPrintTake());
//            queryWrapper.lambda().eq(modelDTO.getIsCancel() != null, CertificateOrder::getIsCancel, modelDTO.getIsCancel());
//            queryWrapper.lambda().eq(modelDTO.getIsReturn() != null, CertificateOrder::getIsReturn, modelDTO.getIsReturn());
//            queryWrapper.lambda().eq(modelDTO.getReturnOrderStatus() != null, CertificateOrder::getReturnOrderStatus, modelDTO.getReturnOrderStatus());
//        }

        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(CertificateOrder::getId, ids);
        }
        queryWrapper.lambda().eq(CertificateOrder::getIsDeleted, BusinessConstant.DELETE_NO);
        List<CertificateOrder> modelList = list(queryWrapper);
        return modelList;
    }

    @Override
    public Boolean createOrderOfCertificate(List<CertificateUser> certificateUserList) {
        Map<Long, List<CertificateUser>> map = certificateUserList.stream().collect(Collectors.groupingBy(CertificateUser::getCompanyId));
        for (Long id : map.keySet()) {
            createOrder(map.get(id).stream().map(CertificateUser::getId).collect(Collectors.toList()));
        }
        return true;
    }


    @Override
    public CertificateOrderVO createOrder(List<Long> certificateUserIdList) {
        //检测信息是否准确
        verify(certificateUserIdList);
        //生成订单
        CertificateOrder certificateOrder = new CertificateOrder();
        certificateOrder.setOrderNumber(orderNumber());
        BigDecimal costMoney = new BigDecimal(0);
        BigDecimal depositMoney = new BigDecimal(0);
        List<CertificateUser> certificateUserList = certificateUserService.list(null, certificateUserIdList);
        Long companyId = null;
        String principalType = null;
        Certificate certificate = certificateService.getByIdCache(certificateUserList.get(0).getCertificateId());
        for (CertificateUser certificateUser : certificateUserList) {
            costMoney = costMoney.add(certificate.getCostMoney());
            depositMoney = depositMoney.add(certificate.getDepositMoney());
            companyId = certificateUser.getCompanyId();
            principalType = certificateUser.getPrincipalType();
        }
        certificateOrder.setCertificateType(CertificateOrderCertificateTypeEnum.get(certificate.getCertificateType().getCode()));
        certificateOrder.setExhibitionId(certificate.getExhibitionId());
        certificateOrder.setCostMoney(costMoney);
        certificateOrder.setDepositMoney(depositMoney);
        certificateOrder.setIsDraw(BusinessConstant.NO);
        certificateOrder.setIsTake(BusinessConstant.NO);
        certificateOrder.setIsPay(BusinessConstant.NO);
        certificateOrder.setOrderStatus(CertificateOrderOrderStatusEnum.NO_PAY);
        certificateOrder.setIsPrintTake(BusinessConstant.NO);
        certificateOrder.setIsCancel(BusinessConstant.NO);
        certificateOrder.setIsReturn(BusinessConstant.NO);
        certificateOrder.setCompanyId(companyId);
        certificateOrder.setCertificateNum(certificateUserList.size());
        certificateOrder.setPrincipalType(principalType);


        BigDecimal takeMoney = new BigDecimal(0);
        takeMoney = certificateOrder.getCostMoney()
                .add(certificateOrder.getDepositMoney() == null ? new BigDecimal(0) : certificateOrder.getDepositMoney());
        if (BigDecimal.ZERO.equals(takeMoney)) {
            certificateOrder.setIsPay(BusinessConstant.YES);
            certificateOrder.setOrderStatus(CertificateOrderOrderStatusEnum.PAY_SUCC);
        }
        save(certificateOrder);
        //调用支付接口
        executePay(certificateOrder);
        //更新制证订单信息
        List<CertificateUser> certificateUserList1 = certificateUserService.list(null, certificateUserIdList);
        for (CertificateUser certificateUser : certificateUserList1) {
            certificateUser.setOrderId(certificateOrder.getId());
            certificateUser.setDrawNumber(certificateOrder.getOrderNumber());
            if (BusinessConstant.YES == certificateOrder.getIsPay()) {
                //状态：已支付
                certificateUser.setIsPay(BusinessConstant.YES);
                certificateUser.setCertificateStatus(CertificateUserCertificateStatusEnum.NO_PRINT);
            } else {
                //状态：待支付
                certificateUser.setCertificateStatus(CertificateUserCertificateStatusEnum.PAY);
            }
            certificateUserService.updateById(certificateUser);
        }
        return doToVo(certificateOrder);
    }

    /**
     * 调用支付接口
     *
     * @param certificateOrder
     */
    public void executePay(CertificateOrder certificateOrder) {
        TransactionOrderDTO transactionOrderDTO = new TransactionOrderDTO();
        //展会信息
        List<Long> exhibitionIds = Arrays.asList(certificateOrder.getExhibitionId());
        ExhibitionManageQuery exhibitionManageQuery = new ExhibitionManageQuery();
        exhibitionManageQuery.setIds(exhibitionIds);
        R<List<ExhibitionManageVO>> listR = exhibitionManageFeign.queryAllExhibitionManage(exhibitionManageQuery);
        if (listR.getIsSuccess() && listR.getData() != null && !listR.getData().isEmpty()) {
            transactionOrderDTO.setExhibitionName(listR.getData().get(0).getExhibitionName());
        }
        //查询服务商信息
        List<Long> companyIds = Arrays.asList(certificateOrder.getCompanyId());
        ServiceProviderDTO query = new ServiceProviderDTO();
        query.setIds(companyIds);
        R<List<ServiceProviderVO>> serviceProviderListR = serviceProviderFeign.queryServiceProvider(query);
        if (serviceProviderListR.getIsSuccess() && serviceProviderListR.getData() != null && !serviceProviderListR.getData().isEmpty()) {
            transactionOrderDTO.setPayer(serviceProviderListR.getData().get(0).getCompanyName());
            transactionOrderDTO.setPayee(serviceProviderListR.getData().get(0).getCompanyName());
        }


        transactionOrderDTO.setExhibitionId(certificateOrder.getExhibitionId());
        transactionOrderDTO.setOrderType(TransactionOrderOrderTypeEnum.CERTIFICATE);
//        transactionOrderDTO.setOrderName();
        transactionOrderDTO.setOrderNum(certificateOrder.getOrderNumber());
        BigDecimal takeMoney = new BigDecimal(0);
        takeMoney = certificateOrder.getCostMoney()
                .add(certificateOrder.getDepositMoney() == null ? new BigDecimal(0) : certificateOrder.getDepositMoney());

        transactionOrderDTO.setOrderAmount(takeMoney);
        transactionOrderDTO.setOrderTime(certificateOrder.getCreateTime());
        transactionOrderDTO.setOrderStatus(TransactionOrderOrderStatusEnum.UNPAY);
        transactionOrderDTO.setPaymentPeriods(1);
        transactionOrderDTO.setPayType(PayTypeEnum.ONLINE_PAY.getCode());
        transactionOrderDTO.setSystemCode(ContextUtil.getSystemScene());
        transactionOrderDTO.setPayee("厦门国贸场馆运营有限公司");
        transactionOrderFeign.save(transactionOrderDTO);
    }

    @Override
    public CertificateOrderVO removeOrder(List<Long> certificateUserIdList) {
        //检测信息是否准确
        List<CertificateUser> certificateUserList = certificateUserService.list(null, certificateUserIdList);
        if (certificateUserList == null || certificateUserList.isEmpty()) {
            throw BizException.wrap(CertificateExceptionCode.CERTIFICATE_NULL);
        }
        for (CertificateUser certificateUser : certificateUserList) {
            if (BusinessConstant.YES == certificateUser.getIsPay()) {
                throw BizException.wrap(CertificateExceptionCode.ORDER_PAY);
            }
        }
        //订单解绑
        for (CertificateUser certificateUser : certificateUserList) {
            certificateUser.setOrderId(null);
            //状态：待提交
            certificateUser.setCertificateStatus(CertificateUserCertificateStatusEnum.SUBMIT);
            certificateUserService.updateById(certificateUser);
        }
        //修改订单
        Long orderId = certificateUserList.get(0).getOrderId();
        CertificateUserDTO certificateUserDTO = new CertificateUserDTO();
        certificateUserDTO.setOrderId(orderId);
        certificateUserList = certificateUserService.list(certificateUserDTO, null);
        CertificateOrder certificateOrder = getByIdCache(orderId);
        BigDecimal costMoney = new BigDecimal(0);
        BigDecimal depositMoney = new BigDecimal(0);
        Certificate certificate = certificateService.getByIdCache(certificateUserList.get(0).getCertificateId());
        for (CertificateUser certificateUser : certificateUserList) {
            costMoney = costMoney.add(certificate.getCostMoney());
            depositMoney = depositMoney.add(certificate.getDepositMoney());
        }
        certificateOrder.setCostMoney(costMoney);
        certificateOrder.setDepositMoney(depositMoney);
        updateById(certificateOrder);
        return doToVo(certificateOrder);
    }

    public String orderNumber() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("cert-");
        stringBuilder.append(new SimpleDateFormat("yyyyMMdd").format(new Date()) + "-");
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        stringBuilder.append(num);
        CertificateOrderDTO certificateOrderDTO = new CertificateOrderDTO();
        certificateOrderDTO.setOrderNumber(stringBuilder.toString());
        List<CertificateOrder> orderList = list(certificateOrderDTO, null);
        if (orderList != null && !orderList.isEmpty()) {
            return orderNumber();
        }
        return stringBuilder.toString();
    }


    @Override
    public R verify(List<Long> certificateUserIdList) {
        //查询用户证件
        List<CertificateUser> certificateUserList = certificateUserService.list(null, certificateUserIdList);
        if (certificateUserList == null || certificateUserList.isEmpty()) {
            throw BizException.wrap(CertificateExceptionCode.CERTIFICATE_NULL);
        }
        Set<Long> companyIdSet = new HashSet<>();
        for (CertificateUser certificateUser : certificateUserList) {
            if (CertificateUserFirstAuthStatusEnum.CHECK_SUCC != certificateUser.getFirstAuthStatus()) {
                throw BizException.wrap(CertificateExceptionCode.CERTIFICATE_FAILNO_ALL);
            }
            if (CertificateUserSecondAuthStatusEnum.CHECK_SUCC != certificateUser.getSecondAuthStatus()) {
                throw BizException.wrap(CertificateExceptionCode.CERTIFICATE_FAILNO_ALL);
            }
            if (certificateUser.getOrderId() != null && certificateUser.getOrderId() > 0) {
                throw BizException.wrap(CertificateExceptionCode.ORDER_EXIST);
            }
            companyIdSet.add(certificateUser.getCompanyId());
        }
        if (companyIdSet.size() > 1) {
            throw BizException.wrap(CertificateExceptionCode.CERTIFICATE_COMPANY_ONLY);
        }
        return null;
    }

    @Override
    public IPage<CertificateOrderVO> pageOrder(PageParams<CertificateOrderDTO> params) {
        CertificateOrderDTO certificateOrderDTO = params.getModel();

        if (certificateOrderDTO != null && StringUtils.isNotBlank(certificateOrderDTO.getFuzzySearch())) {
            //查询公司信息
            ServiceProviderDTO serviceProviderDTO = new ServiceProviderDTO();
            serviceProviderDTO.setCompanyName(certificateOrderDTO.getFuzzySearch());
            serviceProviderDTO.setExhibitionManageId(certificateOrderDTO.getExhibitionId());
            R<List<Long>> listR = serviceProviderFeign.queryServiceProviderIds(serviceProviderDTO);
            if (listR.getIsSuccess() && CollectionUtil.isNotEmpty(listR.getData())) {
                certificateOrderDTO.setCompanyIds(listR.getData());
            }
        }

        boolean isQueryUser = false;
        if (certificateOrderDTO.getCertificateUserDTO() != null && !BeanPlusUtil.checkObjAllFieldsIsNull(certificateOrderDTO.getCertificateUserDTO())) {
            List<CertificateUserVO> certificateUserVOList = certificateUserService.queryFirstAuthForm(certificateOrderDTO.getCertificateUserDTO());

            if (certificateUserVOList != null && !certificateUserVOList.isEmpty()) {
                certificateOrderDTO.setIds(certificateUserVOList.stream().map(CertificateUserVO::getOrderId).collect(Collectors.toList()));
            } else {
                certificateOrderDTO.setIds(new ArrayList<>());
            }
            isQueryUser = true;
        }
        IPage<CertificateOrder> page = params.buildPage();
        QueryWrapper<CertificateOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(certificateOrderDTO.getCompanyId() != null, CertificateOrder::getCompanyId, certificateOrderDTO.getCompanyId())
                .like(StringUtils.isNotBlank(certificateOrderDTO.getOrderNumber()), CertificateOrder::getOrderNumber, "%" + certificateOrderDTO.getOrderNumber() + "%")
                .eq(certificateOrderDTO.getReturnType() != null, CertificateOrder::getReturnType, certificateOrderDTO.getReturnType())
                .eq(certificateOrderDTO.getIsDraw() != null, CertificateOrder::getIsDraw, certificateOrderDTO.getIsDraw())
                .eq(certificateOrderDTO.getIsTake() != null, CertificateOrder::getIsTake, certificateOrderDTO.getIsTake())
                .eq(certificateOrderDTO.getIsPay() != null, CertificateOrder::getIsPay, certificateOrderDTO.getIsPay())
                .eq(certificateOrderDTO.getIsPrintTake() != null, CertificateOrder::getIsPrintTake, certificateOrderDTO.getIsPrintTake())
                .eq(certificateOrderDTO.getIsCancel() != null, CertificateOrder::getIsCancel, certificateOrderDTO.getIsCancel())
                .eq(certificateOrderDTO.getIsReturn() != null, CertificateOrder::getIsReturn, certificateOrderDTO.getIsReturn())
                .eq(certificateOrderDTO.getCertificateType() != null, CertificateOrder::getCertificateType, certificateOrderDTO.getCertificateType())
                .eq(certificateOrderDTO.getExhibitionId() != null, CertificateOrder::getExhibitionId, certificateOrderDTO.getExhibitionId())
                .eq(certificateOrderDTO.getAuthReturnStatus() != null, CertificateOrder::getAuthReturnStatus, certificateOrderDTO.getAuthReturnStatus())
                .le(certificateOrderDTO.getCreateTimeEndTime() != null, CertificateOrder::getCreateTime, certificateOrderDTO.getCreateTimeEndTime())
                .ge(certificateOrderDTO.getCreateTimeStartTime() != null, CertificateOrder::getCreateTime, certificateOrderDTO.getCreateTimeStartTime())

                .eq(certificateOrderDTO.getDrawMakeTime() != null, CertificateOrder::getDrawMakeTime, certificateOrderDTO.getDrawMakeTime())
                .eq(CertificateOrder::getIsDeleted, BusinessConstant.NO);


        if (StringUtils.isNotBlank(certificateOrderDTO.getFuzzySearch())) {
            queryWrapper.lambda().and(wrapper -> {
                wrapper.eq(CertificateOrder::getDrawMobile, TypeHandlerUtil.crypt(certificateOrderDTO.getFuzzySearch()));
                wrapper.or();
                wrapper.like(CertificateOrder::getDrawName, "%" + certificateOrderDTO.getFuzzySearch() + "%");
                wrapper.or();
                wrapper.eq(CertificateOrder::getDrawIdcard, TypeHandlerUtil.crypt(certificateOrderDTO.getFuzzySearch()));
                wrapper.or();
                wrapper.eq(CertificateOrder::getOrderNumber, certificateOrderDTO.getFuzzySearch());
                wrapper.or();
                if (CollectionUtil.isNotEmpty(certificateOrderDTO.getCompanyIds())) {
                    wrapper.in(CertificateOrder::getCompanyId, certificateOrderDTO.getCompanyIds());
                    wrapper.or();
                }
            });
        }


        if (isQueryUser) {
            queryWrapper.lambda().in(CertificateOrder::getId, certificateOrderDTO.getIds());
        }
        //page entity转vo
        IPage<CertificateOrder> certificateUserIPage = page(page, queryWrapper);
        List<CertificateOrderVO> certificateOrderVOList = doToVos(certificateUserIPage.getRecords());
        //组装信息
        assembleBusinssData(certificateOrderVOList);
        IPage<CertificateOrderVO> ipage = ConvertUtil.convertIPage(certificateUserIPage, certificateOrderVOList);
        return ipage;
    }

    public List<CertificateOrderVO> assembleBusinssData(List<CertificateOrderVO> certificateOrderVOList) {
        if (certificateOrderVOList == null || certificateOrderVOList.isEmpty()) {
            return null;
        }
        //下单人信息
        List<Long> userids = certificateOrderVOList.stream().map(CertificateOrderVO::getCreatedBy).collect(Collectors.toList());
        UserAccountDto userAccountDto = new UserAccountDto();
        userAccountDto.setUserIds(userids);
        R<List<UserAccountVo>> userListR = userAccountServiceFeign.querySimpleByIds(userAccountDto);
        if (userListR.getIsSuccess() && userListR.getData() != null && !userListR.getData().isEmpty()) {
            for (UserAccountVo userAccountVo : userListR.getData()) {
                for (CertificateOrderVO certificateOrderVO : certificateOrderVOList) {
                    if (userAccountVo.getId().equals(certificateOrderVO.getCreatedBy())) {
                        certificateOrderVO.setCreateUser(userAccountVo);
                    }
                }
            }
        }
        //查询服务商信息
        List<Long> companyIds = certificateOrderVOList.stream().map(CertificateOrderVO::getCompanyId).collect(Collectors.toList());
        ServiceProviderDTO query = new ServiceProviderDTO();
        query.setIds(companyIds);
        R<List<ServiceProviderVO>> serviceProviderListR = serviceProviderFeign.queryServiceProvider(query);
        if (serviceProviderListR.getIsSuccess() && serviceProviderListR.getData() != null && !serviceProviderListR.getData().isEmpty()) {
            for (ServiceProviderVO serviceProviderVO : serviceProviderListR.getData()) {
                for (CertificateOrderVO certificateOrderVO : certificateOrderVOList) {
                    if (serviceProviderVO.getId().equals(certificateOrderVO.getCompanyId())) {
                        certificateOrderVO.setServiceProviderVO(serviceProviderVO);
                    }
                }
            }
        }
        //展会信息
        List<Long> exhibitionIds = certificateOrderVOList.stream().map(CertificateOrderVO::getExhibitionId).collect(Collectors.toList());
        ExhibitionManageQuery exhibitionManageQuery = new ExhibitionManageQuery();
        exhibitionManageQuery.setIds(exhibitionIds);
        R<List<ExhibitionManageVO>> listR = exhibitionManageFeign.queryAllExhibitionManage(exhibitionManageQuery);
        if (listR.getIsSuccess() && listR.getData() != null && !listR.getData().isEmpty()) {
            for (ExhibitionManageVO exhibitionManageVO : listR.getData()) {
                for (CertificateOrderVO certificateOrderVO : certificateOrderVOList) {
                    if (exhibitionManageVO.getId().equals(certificateOrderVO.getExhibitionId())) {
                        certificateOrderVO.setExhibitionManageVO(exhibitionManageVO);
                    }
                }
            }
        }

        //查询订单发票状态
        for (CertificateOrderVO certificateOrderVO : certificateOrderVOList) {
            //默认未开票
            certificateOrderVO.setInvoiceState("NOT_APPLIED");
        }
        List<Long> buinessIds = certificateOrderVOList.stream().filter(s -> s != null && s.getId() != null).map(CertificateOrderVO::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(buinessIds)) {
            log.info("获取发票信息  businessIds is {}", JSONObject.toJSONString(buinessIds));
            R<List<InvoiceApplyerVO>> listR1 = invoiceApplyerFeign.queryInvoiceExamineState(buinessIds);
            log.info("获取发票信息结果  listR1 is {}", JSONObject.toJSONString(listR1));
            if (listR1.getIsSuccess() && listR1.getData() != null && !listR1.getData().isEmpty()) {
                for (InvoiceApplyerVO invoiceApplyerVO : listR1.getData()) {
                    for (CertificateOrderVO certificateOrderVO : certificateOrderVOList) {
                        if (StringUtils.isNotBlank(invoiceApplyerVO.getBusinessId())
                                && invoiceApplyerVO.getBusinessId().equals(String.valueOf(certificateOrderVO.getId()))
                                && StringUtils.isNotBlank(invoiceApplyerVO.getExamineState())) {
//                        if("INVOICE_RED".equals(invoiceApplyerVO.getExamineState())){
//                            //开票冲红
//                            certificateOrderVO.setInvoiceState("INVOICE_RED");
//                        }else  if("INVOICE_FAIL".equals(invoiceApplyerVO.getExamineState())){
//                            //开票失败
//                            certificateOrderVO.setInvoiceState("INVOICE_FAIL");
//                        }else  if("INVOICE_SUCCESS".equals(invoiceApplyerVO.getExamineState())){
//                            //已开票
//                            certificateOrderVO.setInvoiceState("INVOICED");
//                        }else  if("INVOICE_CANCEL".equals(invoiceApplyerVO.getExamineState())){
//                            //已取消
//                            certificateOrderVO.setInvoiceState("INVOICE_CANCEL");
//                        }else  if("REJECT".equals(invoiceApplyerVO.getExamineState())){
//                            //被驳回
//                            certificateOrderVO.setInvoiceState("REJECTED");
//                        }else  if("INVOICING".equals(invoiceApplyerVO.getExamineState())){
//                            //开票中
//                            certificateOrderVO.setInvoiceState("INVOICING");
//                        }else  if("APPLIED".equals(invoiceApplyerVO.getExamineState())){
//                            //已申请
//                            certificateOrderVO.setInvoiceState("REQUESTED");
//                        }
                            switch (invoiceApplyerVO.getExamineState()) {
                                case "INVOICE_RED":
                                    //开票冲红
                                    certificateOrderVO.setInvoiceState("INVOICE_RED");
                                    break;
                                case "INVOICE_FAIL":
                                    //开票失败
                                    certificateOrderVO.setInvoiceState("INVOICE_FAIL");
                                    break;
                                case "INVOICE_SUCCESS":
                                    //已开票
                                    certificateOrderVO.setInvoiceState("INVOICED");
                                    break;
                                case "INVOICE_CANCEL":
                                    //已取消
                                    certificateOrderVO.setInvoiceState("INVOICE_CANCEL");
                                    break;
                                case "REJECT":
                                    //被驳回
                                    certificateOrderVO.setInvoiceState("REJECTED");
                                    break;
                                case "INVOICING":
                                    //开票中
                                    certificateOrderVO.setInvoiceState("INVOICING");
                                    break;
                                case "APPLIED":
                                    //已申请
                                    certificateOrderVO.setInvoiceState("REQUESTED");
                                    break;
                                default:
                                    certificateOrderVO.setInvoiceState("NOT_APPLIED");
                            }
                        }
                    }
                }
            }
        }
        //查询退单状态
        if (CollectionUtil.isNotEmpty(buinessIds)) {
            for (CertificateOrderVO certificateOrderVO : certificateOrderVOList) {
                //默认未申请
                certificateOrderVO.setReturnOrderStatusOfPay("NOT_APPLIED");
            }
            log.info("查询退单状态  businessIds is {}", JSONObject.toJSONString(buinessIds));
            R<List<ApplyRefundVO>> listR1 = applyRefundFeign.queryRefundExamineState(buinessIds);
            log.info("查询退单状态  listR1 is {}", JSONObject.toJSONString(listR1));
            if (listR1.getIsSuccess() && listR1.getData() != null && !listR1.getData().isEmpty()) {
                for (ApplyRefundVO applyRefundVO : listR1.getData()) {
                    for (CertificateOrderVO certificateOrderVO : certificateOrderVOList) {
                        if (applyRefundVO.getBusinessId() != null
                                && applyRefundVO.getBusinessId().equals(certificateOrderVO.getId())
                                && StringUtils.isNotBlank(applyRefundVO.getExamineState())) {
                            switch (applyRefundVO.getExamineState()) {
                                case "APPLIED":
                                    //已申请
                                    certificateOrderVO.setReturnOrderStatusOfPay("REQUESTED");
                                    break;
                                case "AUTH_FAIL":
                                    //被驳回
                                    certificateOrderVO.setReturnOrderStatusOfPay("REJECTED");
                                    break;
                                case "AUTH_SUCESS":
                                    //已退款
                                    certificateOrderVO.setReturnOrderStatusOfPay("REFUNDED");
                                    break;
                                case "AUTH":
                                    //退款中
                                    certificateOrderVO.setReturnOrderStatusOfPay("REFUNDING");
                                    break;
                                default:
                                    certificateOrderVO.setReturnOrderStatusOfPay("NOT_APPLIED");
                            }
                        }
                    }
                }
            }
        }


        return certificateOrderVOList;
    }


    @Override
    public CertificateOrderVO payOrder(CertificateOrder certificateOrder) {
//        CertificateOrder certificateOrder = getByIdCache(orderId);
        if (certificateOrder == null) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_NUll);
        }
        if (BusinessConstant.YES == certificateOrder.getIsPay()) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_PAY);
        }
        certificateOrder.setIsPay(BusinessConstant.YES);
        certificateOrder.setOrderStatus(CertificateOrderOrderStatusEnum.PAY_SUCC);
        //更新制证订单信息
        CertificateUserDTO certificateUserDTO = new CertificateUserDTO();
        certificateUserDTO.setOrderId(certificateOrder.getId());
        List<CertificateUser> certificateUserList1 = certificateUserService.list(certificateUserDTO, null);
        //添加交易记录
        addPayRecord(certificateOrder);
        updateById(certificateOrder);
        for (CertificateUser certificateUser : certificateUserList1) {
            certificateUser.setIsPay(BusinessConstant.YES);
            //状态：待制证
            certificateUser.setCertificateStatus(CertificateUserCertificateStatusEnum.NO_PRINT);
            certificateUserService.updateById(certificateUser);
        }
        return doToVo(certificateOrder);
    }


    public void addPayRecord(CertificateOrder certificateOrder) {
        CertificateOrderVO certificateOrderVO = new CertificateOrderVO();
        BeanUtils.copyProperties(certificateOrder, certificateOrderVO);
        //组装信息
        List<CertificateOrderVO> certificateOrderVOList = assembleBusinssData(Arrays.asList(certificateOrderVO));
        //保存交易记录
        TransactionDTO transactionDTO = new TransactionDTO();
        transactionDTO.setExhibitionId(certificateOrder.getExhibitionId());
        transactionDTO.setExhibitionName(certificateOrderVOList.get(0).getExhibitionManageVO() == null ? null : certificateOrderVOList.get(0).getExhibitionManageVO().getExhibitionName());
        transactionDTO.setSpaceName(certificateOrderVOList.get(0).getExhibitionSpaceVO() == null ? null : certificateOrderVOList.get(0).getExhibitionSpaceVO().getSpaceName());
        transactionDTO.setSiteName(null);
        transactionDTO.setServiceProviderId(certificateOrderVO.getCompanyId());
        transactionDTO.setServiceProviderName(certificateOrderVOList.get(0).getServiceProviderVO() == null ? null : certificateOrderVOList.get(0).getServiceProviderVO().getCompanyName());
        if (certificateOrderVOList.get(0).getServiceProviderVO() != null && certificateOrderVOList.get(0).getServiceProviderVO().getCompanyType() != null) {
            transactionDTO.setServiceProviderType(certificateOrderVOList.get(0).getServiceProviderVO().getCompanyType().getCode());
        }
        transactionDTO.setOrderType(InvoiceApplyBusinessTypeEnum.Z.getCode());
        transactionDTO.setOrderNum(certificateOrderVO.getOrderNumber());
        transactionDTO.setOrderAmount(queryOrderMoney(certificateOrder.getId()));
        transactionDTO.setOrderTime(LocalDateTime.now());
        transactionDTO.setTransactionType(TranstionTypeEnum.PAYED.getCode());
        transactionDTO.setTransactionState(TransactionStatusEnum.PAYED.getCode());
        transactionDTO.setPayer(null);
        transactionDTO.setPayType(PayTypeEnum.ONLINE_PAY.getCode());
        transactionDTO.setPaymentChannel(PayChannelEnum.OTHER.getCode());
        transactionDTO.setSystemScene(ContextUtil.getSystemScene());

        R<ExhibitorVO> exhibitorVOR = exhibitorFeign.getExhibitor(certificateOrder.getCompanyId());
        log.info("exhibitorVOR is {}", JSONObject.toJSONString(exhibitorVOR));
        if (exhibitorVOR.getIsSuccess() && exhibitorVOR.getData() != null) {
            transactionDTO.setSiteName(exhibitorVOR.getData().getSiteName());
            transactionDTO.setSpaceName(exhibitorVOR.getData().getSpaceName());
        }
        log.info("transactionDTO is {}", JSONObject.toJSONString(transactionDTO));
        transactionFeign.save(transactionDTO);
    }

    @Override
    public CertificateOrderVO cancelOrder(Long orderId) {
        CertificateOrder certificateOrder = getByIdCache(orderId);
        if (certificateOrder == null) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_NUll);
        }
        if (BusinessConstant.YES == certificateOrder.getIsPay()) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_PAY);
        }
        certificateOrder.setIsCancel(BusinessConstant.YES);
        updateById(certificateOrder);

        //更新制证订单信息
        CertificateUserDTO certificateUserDTO = new CertificateUserDTO();
        certificateUserDTO.setOrderId(certificateOrder.getId());
        List<CertificateUser> certificateUserList1 = certificateUserService.list(certificateUserDTO, null);
        for (CertificateUser certificateUser : certificateUserList1) {
            //状态：待提交
            certificateUser.setCertificateStatus(CertificateUserCertificateStatusEnum.SUBMIT);
            certificateUser.setOrderId(null);
            certificateUserService.updateById(certificateUser);
        }

        //取消订单
        transactionOrderFeign.cancel(certificateOrder.getOrderNumber());
        return doToVo(certificateOrder);
    }

    @Override
    public CertificateOrderVO drawOrder(CertificateOrderDTO certificateOrderDTO) {
        CertificateOrder certificateOrder = getByIdCache(certificateOrderDTO.getId());
        if (certificateOrder == null) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_NUll);
        }
        if (BusinessConstant.NO == certificateOrder.getIsPay()) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_PAY_NO);
        }

        if (BusinessConstant.NO == certificateOrder.getIsPrintTake()) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_PRINT_NO);
        }
        certificateOrder.setDrawNameEnd(certificateOrderDTO.getDrawName());
        certificateOrder.setDrawMobileEnd(certificateOrderDTO.getDrawMobile());
        certificateOrder.setDrawIdcardEnd(certificateOrderDTO.getDrawIdcard());
        if (certificateOrderDTO.getDrawTime() != null) {
            certificateOrder.setDrawTime(certificateOrderDTO.getDrawTime());
        }
        if (CertificateOrderDrawTypeEnum.SITE.eq(certificateOrder.getDrawType()) && certificateOrderDTO.getDrawTime() == null) {
            certificateOrder.setDrawTime(LocalDateTime.now());
        }
        if (certificateOrderDTO.getDrawMakeTime() != null) {
            certificateOrder.setDrawMakeTime(certificateOrderDTO.getDrawMakeTime());
        }
        certificateOrder.setIsDraw(BusinessConstant.YES);
        updateById(certificateOrder);

        //更新制证订单信息
        CertificateUserDTO certificateUserDTO = new CertificateUserDTO();
        certificateUserDTO.setOrderId(certificateOrder.getId());
        List<CertificateUser> certificateUserList1 = certificateUserService.list(certificateUserDTO, null);
        for (CertificateUser certificateUser : certificateUserList1) {
            //状态：已领取
            certificateUser.setCertificateStatus(CertificateUserCertificateStatusEnum.DRAW);
            certificateUser.setDrawIdcard(certificateOrderDTO.getDrawIdcard());
            certificateUser.setDrawMobile(certificateOrderDTO.getDrawMobile());
            certificateUser.setDrawName(certificateOrderDTO.getDrawName());
            certificateUser.setIsDraw(BusinessConstant.YES);
            certificateUserService.updateById(certificateUser);
        }
        return doToVo(certificateOrder);

    }

    @Override
    public CertificateOrderVO makeDrawOrder(CertificateOrderDTO certificateOrderDTO) {
        CertificateOrder certificateOrder = getByIdCache(certificateOrderDTO.getId());
        if (certificateOrder == null) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_NUll);
        }
        if (BusinessConstant.NO == certificateOrder.getIsPay()) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_PAY_NO);
        }
        certificateOrder.setDrawMakeTime(certificateOrderDTO.getDrawMakeTime());
        certificateOrder.setDrawName(certificateOrderDTO.getDrawName());
        certificateOrder.setDrawIdcard(certificateOrderDTO.getDrawIdcard());
        certificateOrder.setDrawMobile(certificateOrderDTO.getDrawMobile());
        certificateOrder.setDrawType(certificateOrderDTO.getDrawType());
        updateById(certificateOrder);
        return doToVo(certificateOrder);
    }

    @Override
    public CertificateOrderVO takeOrder(Long orderId) {
        CertificateOrder certificateOrder = getByIdCache(orderId);
        if (certificateOrder == null) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_NUll);
        }
        if (BusinessConstant.NO == certificateOrder.getIsPay()) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_PAY_NO);
        }
        certificateOrder.setIsTake(BusinessConstant.YES);
        updateById(certificateOrder);
        return doToVo(certificateOrder);
    }

    @Override
    public CertificateOrderVO executeReturnOrder(CertificateOrderDTO certificateOrderDTO) {
        CertificateOrder certificateOrder = getByIdCache(certificateOrderDTO.getId());
        if (certificateOrder == null) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_NUll);
        }
        if (BusinessConstant.NO == certificateOrder.getIsPay()) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_PAY_NO);
        }
        certificateOrderDTO.setReturnMoney(queryReturnMoney(certificateOrderDTO.getId()));
        BeanUtils.copyProperties(certificateOrderDTO, certificateOrder);
//        certificateOrder.setReturnOrderStatus(CertificateOrderReturnOrderStatusEnum.REFUND);
        certificateOrder.setAuthReturnStatus(CertificateOrderAuthReturnStatusEnum.AUTH);
        certificateOrder.setIsReturn(BusinessConstant.YES);
        updateById(certificateOrder);
        return doToVo(certificateOrder);
    }

    @Override
    public BigDecimal queryReturnMoney(Long id) {
        CertificateOrder certificateOrder = getByIdCache(id);
        //退款金额
        BigDecimal returnMoney = new BigDecimal(0);
        returnMoney = certificateOrder.getDepositMoney()
                .subtract(certificateOrder.getOverTimeMoney() == null ? new BigDecimal(0) : certificateOrder.getOverTimeMoney());
        if (returnMoney.compareTo(BigDecimal.ZERO) >= 1) {
            return returnMoney;
        } else {
            return new BigDecimal(0);
        }
    }

    @Override
    public BigDecimal queryTakeMoney(Long id) {
        CertificateOrder certificateOrder = getByIdCache(id);
        //发票金额
        BigDecimal takeMoney = new BigDecimal(0);
//        takeMoney = certificateOrder.getCostMoney()
//                .add(certificateOrder.getDepositMoney() == null ? new BigDecimal(0) : certificateOrder.getDepositMoney());

        takeMoney = certificateOrder.getCostMoney();
        if (takeMoney.compareTo(BigDecimal.ZERO) >= 1) {
            return takeMoney;
        } else {
            return new BigDecimal(0);
        }
    }

    @Override
    public BigDecimal queryOrderMoney(Long id) {
        CertificateOrder certificateOrder = getByIdCache(id);
        //发票金额
        BigDecimal takeMoney = new BigDecimal(0);
        if (certificateOrder.getCostMoney() != null) {
            takeMoney = certificateOrder.getCostMoney()
                    .add(certificateOrder.getDepositMoney() == null ? new BigDecimal(0) : certificateOrder.getDepositMoney());
        }
        if (takeMoney.compareTo(BigDecimal.ZERO) >= 1) {
            return takeMoney;
        } else {
            return new BigDecimal(0);
        }
    }

    @Override
    public Boolean takeRate(TakeApplyerDTO takeApplyerDTO) {
        List<CertificateOrder> certificateOrderList = list(null, takeApplyerDTO.getOrderIds());
        if (certificateOrderList == null || certificateOrderList.isEmpty()) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_NUll);
        }
        for (CertificateOrder certificateOrder : certificateOrderList) {
            if (BusinessConstant.YES != certificateOrder.getIsPay()) {
                throw BizException.wrap(CertificateExceptionCode.ORDER_PAY_NO);
            }
        }
        Map<Long, List<CertificateOrder>> groupList = certificateOrderList.stream().collect(Collectors.groupingBy(CertificateOrder::getCompanyId));
        if (groupList.keySet().size() > 1) {
            throw BizException.wrap(CertificateExceptionCode.CERTIFICATE_COMPANY_ONLY);
        }
        for (List<CertificateOrder> certificateOrderList1 : groupList.values()) {
            List<CertificateOrderVO> certificateOrderVOList = doToVos(certificateOrderList1);
            //发票金额
            BigDecimal invoiceAmount = new BigDecimal(0);
            for (CertificateOrderVO certificateOrderVO : certificateOrderVOList) {
                invoiceAmount = invoiceAmount.add(queryTakeMoney(certificateOrderVO.getId()));
            }
            //组装信息
            assembleBusinssData(certificateOrderVOList);
            InvoiceApplyerDTO invoiceApplyerDTO = new InvoiceApplyerDTO();
            BeanUtils.copyProperties(takeApplyerDTO, invoiceApplyerDTO);
            invoiceApplyerDTO.setBusinessType("制证发票");
            invoiceApplyerDTO.setCutomerId(certificateOrderVOList.get(0).getCompanyId());
            invoiceApplyerDTO.setCutomerName(certificateOrderVOList.get(0).getServiceProviderVO().getCompanyName());
            invoiceApplyerDTO.setInvoiceTitle(certificateOrderVOList.get(0).getServiceProviderVO().getCompanyName());
            invoiceApplyerDTO.setInvoiceDutyParagraph(certificateOrderVOList.get(0).getServiceProviderVO().getUscc());
//                invoiceApplyerDTO.setCostType();
            invoiceApplyerDTO.setCompanyAddress(certificateOrderVOList.get(0).getServiceProviderVO().getCompanyAddress());
            invoiceApplyerDTO.setCompanyTel(certificateOrderVOList.get(0).getServiceProviderVO().getCompanyPhone());
            invoiceApplyerDTO.setExhibitionId(certificateOrderVOList.get(0).getExhibitionId());
            invoiceApplyerDTO.setExhibitionName(certificateOrderVOList.get(0).getExhibitionManageVO().getExhibitionName());
            invoiceApplyerDTO.setBankAccountNum(certificateOrderVOList.get(0).getServiceProviderVO().getBankAccount());
            invoiceApplyerDTO.setBankName(certificateOrderVOList.get(0).getServiceProviderVO().getBankName());
            invoiceApplyerDTO.setInvoiceAmount(invoiceAmount);
//            invoiceApplyerDTO.setBusinessIds(certificateOrderVOList.stream().map(CertificateOrderVO::getId).collect(Collectors.toList()));
            invoiceApplyerDTO.setBusinessId(certificateOrderVOList.get(0).getServiceProviderVO().getId() + "");
            R r = invoiceApplyerFeign.saveInvoiceApplyer(invoiceApplyerDTO);
            if (r.getIsSuccess()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public CertificateOrderVO authReturnOrder(Long orderId, Boolean isAuth) {
        CertificateOrder certificateOrder = getByIdCache(orderId);
        if (certificateOrder == null) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_NUll);
        }
        if (BusinessConstant.NO == certificateOrder.getIsPay()) {
            throw BizException.wrap(CertificateExceptionCode.ORDER_PAY_NO);
        }
        if (isAuth) {
            certificateOrder.setAuthReturnStatus(CertificateOrderAuthReturnStatusEnum.AUTH_SUCESS);
            certificateOrder.setReturnOrderStatus(CertificateOrderReturnOrderStatusEnum.REFUND);
        } else {
            certificateOrder.setAuthReturnStatus(CertificateOrderAuthReturnStatusEnum.AUTH_FAIL);
            certificateOrder.setReturnOrderStatus(CertificateOrderReturnOrderStatusEnum.NO_REFUND);
        }
        updateById(certificateOrder);
        return doToVo(certificateOrder);
    }

    @Override
    public CertificateOrderVO detail(Long orderId) {
        CertificateOrder certificateOrder = getByIdCache(orderId);
        CertificateUserDTO certificateUserDTO = new CertificateUserDTO();
        certificateUserDTO.setOrderId(orderId);
        List<CertificateUser> certificateUserList = certificateUserService.list(certificateUserDTO, null);
        CertificateOrderVO certificateOrderVO = doToVo(certificateOrder);
        certificateOrderVO.setCertificateUserVOList(certificateUserService.doToVos(certificateUserList));
        //组装信息
        assembleBusinssData(Arrays.asList(certificateOrderVO));
        return certificateOrderVO;
    }

    @Override
    public Boolean makeCertificate(CertificateUserDTO certificateUserDTO) {
        List<CertificateUser> certificateUserList = certificateUserService.list(null, certificateUserDTO.getIds());
        List<CertificateUser> newlist = new ArrayList<>();
        for (CertificateUser certificateUser : certificateUserList) {
            if (BusinessConstant.YES == certificateUser.getIsBlack()) {
                throw BizException.wrap(String.format("%s是黑名单不能补证", certificateUser.getCardNumber()));
            }
            CertificateUser certificateUser1 = new CertificateUser();
            BeanUtils.copyProperties(certificateUser, certificateUser1);
            certificateUser1.setId(null);
            certificateUser1.setIsEnabled(BusinessConstant.YES);
            certificateUser1.setIsDeleted(BusinessConstant.NO);
            certificateUser1.setFirstAuthStatus(CertificateUserFirstAuthStatusEnum.CHECK_SUCC);
            certificateUser1.setSecondAuthStatus(CertificateUserSecondAuthStatusEnum.CHECK_SUCC);
            certificateUser1.setIsCancel(BusinessConstant.NO);
            certificateUser1.setIsLoss(BusinessConstant.NO);
            certificateUser1.setIsDraw(BusinessConstant.NO);
            certificateUser1.setIsPay(BusinessConstant.NO);
            certificateUser1.setIsBlack(BusinessConstant.NO);
            certificateUser1.setIsPrintTake(BusinessConstant.NO);
            certificateUser1.setCertificateStatus(CertificateUserCertificateStatusEnum.PAY);
            certificateUser1.setOrderId(null);
            newlist.add(certificateUser1);

            //修改补证状态
            certificateUser.setIsMake(BusinessConstant.YES);
            certificateUserService.updateById(certificateUser);
        }
        for (CertificateUser certificateUser : newlist) {
            certificateUserService.save(certificateUser);
        }
        createOrderOfCertificate(newlist);
        return true;
    }


    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public CertificateOrderVO doToVo(CertificateOrder model) {
        CertificateOrderVO modelVo = new CertificateOrderVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        modelVo.setCreatedBy(model.getCreatedBy());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<CertificateOrderVO> doToVos(List<CertificateOrder> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<CertificateOrderVO> result = new ArrayList<>();
        for (CertificateOrder model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {
        return new CertificateOrderCacheKeyBuilder();
    }
}
